package com.ywjt.platformbusiness.market.commongoods.view;

import android.content.Context;
import android.graphics.Paint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseBottomDialog;
import com.ywjt.platformbusiness.market.GoodsSpVOListDTO;
import com.ywjt.platformbusiness.market.commongoods.model.GoodsDetail;
import com.ywjt.platformbusiness.market.commongoods.model.ParameterEntity;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.widget.FlowLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class BottomGoodSelectDialog extends BaseBottomDialog implements View.OnClickListener {
    private ImageView ivGoodsImg;
    private TextView tvPrice;
    private TextView tvStock;
    private RecyclerView rcSku;
    private TextView tvSure;
    private TextView tvChiose;
    private ImageView dialogClose;
    private ImageView ivMinus;//减减
    private ImageView ivAdd;//加加
    private TextView tvNum;//数量
    private int num=1;

    private Context context;
    private SpecAdapter mAdapter;
    private int type=0;
    private GoodsDetail goodsDetail;
    private StringBuffer strSku=null;
    private int stock=0;
    private String skuId="";
    private int skuPosi=0;



    private HashMap<Integer, List<ParameterEntity>> outMap;
    private List<GoodsDetail.ResultDTO.GoodsSkuListDTO> skuList;
    private List<GoodsSpVOListDTO> specList;
    private boolean allSelected = false;
    private GoodsDetail.ResultDTO.GoodsSkuListDTO selectedSku;
    private SelectedListener selectedListener;
    private boolean hasChanged;

    public BottomGoodSelectDialog(Context context,GoodsDetail goodsDetail) {
        this.context = context;
        this.goodsDetail=goodsDetail;
    }


    @Override
    public int getLayoutRes() {
        return R.layout.bottomgoodselectdialog;
    }

    @Override
    public void bindView(View v) {
        skuList=goodsDetail.getResult().getGoodsSkuList();

        ivGoodsImg=v.findViewById(R.id.ivGoodsImg);
        tvPrice=v.findViewById(R.id.tvPrice);
        tvStock=v.findViewById(R.id.tvStock);
        rcSku=v.findViewById(R.id.rcSku);
        tvSure=v.findViewById(R.id.tvSure);
        tvChiose=v.findViewById(R.id.tvChiose);
        dialogClose=v.findViewById(R.id.dialogClose);
        ivMinus=v.findViewById(R.id.ivMinus);
        ivAdd=v.findViewById(R.id.ivAdd);
        ivAdd.setOnClickListener(this::onClick);
        ivMinus.setOnClickListener(this::onClick);
        tvNum=v.findViewById(R.id.tvNumber);
        tvNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    try {
                        num = Integer.parseInt(s.toString());
                        ivMinus.setEnabled(true);
                        ivAdd.setEnabled(true);
                        if (num <= 1) {
                            ivMinus.setEnabled(false);
                            if (!hasChanged) {
                                hasChanged = true;
                                tvNum.setText("1");
                                hasChanged = false;
                            }
                        }
                        if (num >= selectedSku.getStock()) {
                            num = selectedSku.getStock();
                            ivAdd.setEnabled(false);
                        }
                        if (!hasChanged) {
                            hasChanged = true;
                            tvNum.setText(String.valueOf(num));
                            hasChanged = false;
                        }
                        tvNum.setText(tvNum.getText().toString().length());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        dialogClose.setOnClickListener(this);
        tvSure.setOnClickListener(this);



        try {
            JSONArray jsonArray = new JSONArray(goodsDetail.getResult().getSpecification());
            specList=new ArrayList<>();
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject= (JSONObject) jsonArray.get(i);

                    GoodsSpVOListDTO bean=new GoodsSpVOListDTO();
                    bean.setKey(jsonObject.getString("key"));;
                    JSONArray array=jsonObject.getJSONArray("values");
                    List<GoodsSpVOListDTO.ValuesDTO> beanlist=new ArrayList<>();
                    for (int j=0;j<array.length();j++){
                        GoodsSpVOListDTO.ValuesDTO beans=new GoodsSpVOListDTO.ValuesDTO();
                        JSONObject jsonObject1=(JSONObject)array.get(j);
                        beans.setValue(jsonObject1.getString("value"));
                        beanlist.add(beans);
                    }

                    bean.setValues(beanlist);
                    specList.add(bean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        setView();
    }


    public void setView(){
        outMap=new HashMap<>();
        for (int i = 0; i < specList.size(); i++) {
            GoodsSpVOListDTO specBean = specList.get(i);
            List<ParameterEntity> innerList = new ArrayList();
            for (int j = 0; j < specBean.getValues().size(); j++) {
                ParameterEntity entity = new ParameterEntity(specBean.getValues().get(j).getValue());
                entity.selected = false;
                innerList.add(entity);
            }
            outMap.put(i, innerList);
        }

        mAdapter = new SpecAdapter(specList);
        rcSku.setLayoutManager(new LinearLayoutManager(context));
        rcSku.setAdapter(mAdapter);

        Glide.with(context).load(goodsDetail.getResult().getMainPhoto())
                .placeholder(R.mipmap.icon_classify_default_img)
                .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(5)))
                .into(ivGoodsImg);
        tvPrice.setText("￥"+goodsDetail.getResult().getPrice());

        for (int i=0;i<goodsDetail.getResult().getGoodsSkuList().size();i++){
            stock=stock+goodsDetail.getResult().getGoodsSkuList().get(i).getStock();
        }

        tvStock.setText("库存"+stock);
        strSku=new StringBuffer();
        tvChiose.setText("请选择商品规格");
        checkEnable();
    }

    public void setClicklistener(ClickLintener clickListener) {
        lintener = clickListener;
    }

    private ClickLintener lintener;

    public interface ClickLintener{
        void  confirm(int num,String skuId,String price);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.dialogClose:
                dismiss();
                break;
            case R.id.tvSure:
                if(skuId.equals("")){
                    Toast.makeText(context,"请选择商品规格",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    lintener.confirm(num,skuId,selectedSku.getPrice().toString());
                }
                break;
            case R.id.tvAdd:
                num++;
                tvNum.setText(num+"");
                break;
            case R.id.ivMinus:
                if(num>1){
                    num--;
                }
                tvNum.setText(num+"");
                break;
        }
    }


    public void setSkuPrice(){
        Glide.with(context).load(selectedSku.getImg()).placeholder(R.mipmap.icon_classify_default_img)
                .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(5)))
                .into(ivGoodsImg);
        tvPrice.setText("￥"+selectedSku.getPrice());
        tvStock.setText("库存"+selectedSku.getStock());

        strSku=new StringBuffer();

        try {
            JSONArray jsonArray = new JSONArray(selectedSku.getSpData());
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                strSku.append(" "+jsonObject.getString("value"));
            }
            tvChiose.setText("已选:"+strSku);
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    /*******/

    class SpecAdapter extends RecyclerView.Adapter<SpecAdapter.ViewHolder> {
        private List<GoodsSpVOListDTO> data;

        public SpecAdapter(List<GoodsSpVOListDTO> data) {
            this.data = data;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ViewHolder holder = new ViewHolder(LayoutInflater.from(
                    context).inflate(R.layout.item_goods_sku_parent, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            GoodsSpVOListDTO specBean = data.get(position);
            holder.tvkey.setText(specBean.getKey());
            holder.flContainer.setHorizontalSpacing(30);
            holder.flContainer.setVerticalSpacing(20);
            ArrayList<ParameterEntity> list = new ArrayList<>();
            for (int i = 0; i < specBean.getValues().size(); i++) {
                ParameterEntity entity = new ParameterEntity(specBean.getValues().get(i).getValue());
                entity.enable = computEnable(position, entity.name);
                entity.selected = outMap.get(position).get(i).selected;
                list.add(entity);
            }
            AttrAdapter attrAdapter = new AttrAdapter(position, list);
            holder.flContainer.setAdapter(attrAdapter);
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvkey;
            FlowLayout flContainer;

            public ViewHolder(View itemView) {
                super(itemView);
                tvkey = (TextView) itemView.findViewById(R.id.tvkey);
                flContainer = (FlowLayout) itemView.findViewById(R.id.rcSkus);
            }
        }
    }


    class AttrAdapter extends BaseAdapter {
        private int outPosition;
        private List<ParameterEntity> list;
        public AttrAdapter( int position, List<ParameterEntity> list) {
            this.outPosition = position;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.isEmpty() ? null : list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            final Holder holder;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(R.layout.item_flow, null);
                holder = new Holder(view);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            ParameterEntity param = list.get(position);
            holder.tv.setText(param.name);
            holder.tv.setEnabled(param.enable);
            holder.tv.setSelected(param.selected);

            if(!param.enable){
                //不能点击
                holder.tv.setTextColor(getResources().getColor(R.color.gray9));
                holder.tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
            }else{
                if(param.selected){
                    holder.tv.setTextColor(getResources().getColor(R.color.red));
                    holder.tv.setBackground(getResources().getDrawable(R.drawable.stock_red_bg_5));
                }else {
                    holder.tv.setTextColor(getResources().getColor(R.color.gray3));
                }
            }

            holder.tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!v.isEnabled()) return;
                    List<ParameterEntity> innerList = outMap.get(outPosition);
                    for (int i = 0; i < innerList.size(); i++) {
                        innerList.get(i).selected = false;
                    }
                    innerList.get(position).selected = !holder.tv.isSelected();
                    mAdapter.notifyDataSetChanged();
                   checkAllChecked();
                }
            });
            return view;
        }
    }
    class Holder {
        TextView tv;

        public Holder(View view) {
            tv=view.findViewById(R.id.text);
        }
    }

    /**
     * 计算是否可以点击
     *
     * @return
     */
    private boolean computEnable(int position, String spacValue) {
        boolean result = false;
        HashMap<Integer, String> selectedMap = new HashMap<>();//已选的属性，key为属性序列，value为属性值
        Iterator<Map.Entry<Integer, List<ParameterEntity>>> entries = outMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, List<ParameterEntity>> entry = entries.next();
            List<ParameterEntity> value = entry.getValue();
            String selected = null;
            for (int i = 0; i < value.size(); i++) {
                if (value.get(i).selected) {
                    selected = value.get(i).name;
                }
            }
            if (selected != null && entry.getKey() != position) {//后一个条件使选中的属性的兄弟属性得以选择
                selectedMap.put(entry.getKey(), selected);
            }
        }
        ArrayList<GoodsDetail.ResultDTO.GoodsSkuListDTO> matchedSku = new ArrayList<>();//筛选出符合 选中要求的sku
        for (int i = 0; i < skuList.size(); i++) {
            boolean matche = true;
            GoodsDetail.ResultDTO.GoodsSkuListDTO sku = skuList.get(i);
            Iterator<Map.Entry<Integer, String>> e = selectedMap.entrySet().iterator();
            while (e.hasNext()) {
                Map.Entry<Integer, String> next = e.next();

                JSONArray jsonArray1 = null;
                try {
                    jsonArray1 = new JSONArray(sku.getSpData());
                    JSONObject jsonObject1=(JSONObject)jsonArray1.get(next.getKey());

                    if (!jsonObject1.getString("value").equals(next.getValue())) {
                        matche = false;
                    }
                } catch (JSONException jsonException) {
                    jsonException.printStackTrace();
                }
            }
            if (matche) {
                matchedSku.add(sku);
            }
        }
        //遍历符合要求的sku，如果sku中有该选项，且库存不为零，则可选
        for (int i = 0; i < matchedSku.size(); i++) {
            GoodsDetail.ResultDTO.GoodsSkuListDTO sku = matchedSku.get(i);
            try {
                JSONArray jsonArray1 = new JSONArray(sku.getSpData());
                JSONObject jsonObject1=jsonArray1.getJSONObject(position);
                if (jsonObject1.getString("value").equals(spacValue) && sku.getStock() >= 1) {
                    result = true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
        return result;
    }
    private void checkAllChecked() {
        int selectedCount = 0;
        StringBuilder stringBuilder = new StringBuilder();
        Iterator<Map.Entry<Integer, List<ParameterEntity>>> entries = outMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, List<ParameterEntity>> entry = entries.next();
            List<ParameterEntity> value = entry.getValue();
            for (int i = 0; i < value.size(); i++) {
                if (value.get(i).selected) {
                    selectedCount++;
                    stringBuilder.append(value.get(i).name + " ");
                }
            }
        }
        String paramString = stringBuilder.toString();
        if (selectedCount == specList.size()) {
            allSelected = true;
            String[] split = paramString.trim().split(" ");
            for (int i = 0; i < skuList.size(); i++) {

                try {
                    JSONArray jsonArray = new JSONArray(skuList.get(i).getSpData());
                    for (int j = 0; j <jsonArray.length() ; j++) {

                        ArrayList<String> strings = new ArrayList<>();

                        String strs="";
                        JSONArray jsonArray1 = new JSONArray(goodsDetail.getResult().getGoodsSkuList().get(i).getSpData());
                        for(int m=0;m<jsonArray1.length();m++){
                            JSONObject jsonObject1=jsonArray1.getJSONObject(m);
                            strs=strs+jsonObject1.getString("value");
                        }
                        strings.add(strs);

                        String tt="";
                        for(int n=0;n<Arrays.asList(split).size();n++){
                            tt=tt+Arrays.asList(split).get(n);
                        }

                        strings.remove(tt);
                        if (strings.size() == 0) {
                            selectedSku = skuList.get(i);
                            skuPosi=i;
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }
            checkEnable();
            //设置上面的数据
            setSkuPrice();
            skuId=selectedSku.getId()+"";


            if (selectedListener != null) {
                selectedListener.onSlectedChanged(true, paramString);
            }
        } else {
            allSelected = false;
            selectedSku = null;
            ivAdd.setEnabled(false);
            ivMinus.setEnabled(false);
            tvNum.setEnabled(false);
            if (selectedListener != null) {
                selectedListener.onSlectedChanged(false, null);
            }
        }
    }



    private boolean checkEnable() {
        boolean enable = true;
        if (!allSelected) {
            ivAdd.setEnabled(false);
            ivMinus.setEnabled(false);
            tvNum.setEnabled(false);
        } else {
            ivAdd.setEnabled(true);
            ivMinus.setEnabled(true);
            tvNum.setEnabled(true);
            if (num <= 1) {
                num = 1;
                ivMinus.setEnabled(false);
                if (num < 1) {
                    enable = false;
                }
            }
            if (num >= selectedSku.getStock()) {
                num = selectedSku.getStock();
                ivAdd.setEnabled(false);
                if (num > selectedSku.getStock()) {
                    enable = false;
                }
            }
            tvNum.setText(String.valueOf(num));
        }
        return enable;
    }


    public interface SelectedListener {
        void onSlectedChanged(boolean allSelected, String param);
    }
}